<template>
    <fieldset>
        <legend>二级联动</legend>
        省:
        <select v-model="sel1" @change="provienceChange(sel1)">
            <option v-for="item in provience" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>
        市:
        <select v-model="sel2" @change="cityChange(sel2)">
            <option v-for="item in citys" :key="item.id" :value="item.id">
                {{item.name}}
            </option>
        </select>
        县:
        <select v-model="sel3">
            <option v-for="item in county" :key="item.id" :value="item.id">
                {{item.name}}
            </option>
        </select>
    </fieldset>
</template>
<script>
    import * as api from "@/api/select"
    export default {
        data(){
            return {
                //省的数据
                provience:[],
                //市的数据
                citys:[],
                //县的数据
                county:[],
                //选中的省的id
                sel1:"1",
                //选中市的id
                sel2:"",
                //选中县的id
                sel3:""
            }
        },
        
        mounted(){
            api.fetchData()
            .then(res => {
                console.log(res)
                //获去了所有的数据
                // let data = res.data.data;
                // this.provience = data.filter(item => item.parentId === 0)
                this.provience = res;
                //获取默认第一条的id
                let pid = res[0].id
                this.provienceChange(pid)
            })

            // api.fetchCity(2)
            // .then(res=>{
            //     console.log(res)
            // })
        },
        methods:{
            provienceChange(pid){
                //选择的省变化的时候，获取选择的省对应的Id，发起请求，请求市的数据
                api.fetchCity(pid)
                .then(res=>{
                    console.log(res)
                    this.citys = res;
                    //默认选中
                    if(res.length > 0){
                        this.sel2 = res[0].id
                    }
                    let cid = res[0].id
                    this.cityChange(cid)

                })
            },
            cityChange(cid){
                //选择的市变化的时候，获取选择的市对应的Id，发起请求，请求县的数据
                api.fetchCity(cid)
                .then(res=>{
                    console.log(res)
                    this.county = res
                    //默认选中
                    if(res.length>0){
                        this.sel3 = res[0].id
                    }
                })
            }
            
        },
    }
</script>
<style scoped>
    select {
        width: 100px;
    }
</style>
